<template>
  <div class="page-container">
    <signature
        :propVisible="signatureVisible"
        :propHeight="300"
        @confirm="handleSignatureComplete"
        @cancel="handleCancelSign"
      />
    <van-cell-group>
      <van-field
        ref="scanDom"
        v-model="scan"
        label=""
        label-width="130"
        left-icon="scan"
        style="background-color:lightYellow"
        placeholder="扫描配送单号/物品码"
        size="large"
        clearable
        border
        @keyup.enter.native="handleScanOver"
        @clear="handleScanClear"
        @click-left-icon="handleScanClear"
      />

      <van-field label="配送单号:" label-align="right" v-model="dist.busKey" size="mini" disabled />
      <van-field label="金额:" label-align="right" v-model="dist.amount" size="mini" disabled />
      <van-field label="科室:" label-align="right" v-model="dist.deptName"  size="mini" disabled />
      <van-field label="收货人:" label-align="right" ref="receiverDOM" v-model="dist.receiver"  size="mini" class="edit-field" right-icon="edit"/>
    </van-cell-group>
    <van-divider><span style="font-size:9px">配送单明细</span></van-divider>
    <div class="items-container">
      <van-collapse v-model="activeNames">
        <van-collapse-item
          v-for="distItem in distItems"
          :key="distItem.id"
          :name="distItem.id">
          <template #title>
            <div>
              <span class="matr-name">{{distItem.matrName}}</span>
            </div>
            <div>
              <span class="matr-spec">{{distItem.matrSpec}}</span>
            </div>
          </template>
          <template #value>
            <div class="value-container">
              <div><van-icon name="shopping-cart-o" /><label class="matr-qty">{{distItem.pickedSkuQty}}</label></div>
              <div><van-icon name="scan" /><label class="matr-qty">{{distItem.scanedSkuQty}}</label></div>
              <div>{{distItem.skuUnit}}</div>
            </div>
          </template>
          <template #right-icon>
            <div class="icon-container">
              <van-icon :name="getIcon(distItem,'name')" :class="getIcon(distItem,'class')" />
              <van-icon name="arrow-down" :class="getIcon(distItem,'class')" />
            </div>
          </template>
          <template>
            <div>
              <receive-item propTitleMode />
              <receive-item
                v-for="pickItem in getPickItems(distItem)"
                :key="pickItem.id"
                :value="pickItem"
              />
            </div>
          </template>
        </van-collapse-item>
      </van-collapse>
    </div>
    <div class="btn-container" v-if="dist.id">

      <flow-buttons
        :propFlowKey="propFlowKey"
        plain
        @button-click="handleFlowButtonClick"
        style="width:100%" />
    </div>
  </div>
</template>

<script>
import FlowButtons from '@/components/FlowButtons'
import Signature from '@/components/Signature'
import ReceiveItem from './ReceiveItem'


export default {
  data() {
    return {
      activeNames: [],
      scan: '',
      dist: {},
      distItems: [],
      pickItems: [],
      signatureVisible: false,
      flowButton: {}
    }
  },
  props: {
    propFlowKey: String
  },
  mounted() {
    this.$refs.scanDom.focus()
  },
  computed: {
    cpButtonDisable() {
      return !this.dist.id
    }
  },
  methods: {
    getFlowNodeValue() {
      if (this.propFlowKey) {
        return this.propFlowKey.split(':')[1]
      }
    },
    getPickItems(distItem) {
      return this.pickItems.filter(item => item.distItemId == distItem.id)
    },
    getIcon(distItem, type) {
      if (distItem.scanedSkuQty == distItem.pickedSkuQty) {
        return type == 'name' ? 'passed' : 'passed'
      } else {
        return type == 'name' ? 'warning-o' : 'warning'
      }
    },
    getScanType(source) {
      const prefix1 = source.substring(0, 1)
      if (prefix1 == 'D') {
        return 'dist'
      } else if (prefix1 == 'F') {
        return 'rfid'
      } else  {
        return 'sn'
      }
    },
    setActiveName(uc, ucType) {
      const pickItem = this.pickItems.find(item => item[ucType] == uc)
      this.activeNames = [pickItem.distItemId]
    },
    handleScanClear(event) {
      this.scan = ''
    },
    handleScanOver() {
      if (window.isPDAScan()) this.scan = window.getPDAScan()
      if (!this.scan) return
      const scanType = this.getScanType(this.scan)
      if (scanType == 'dist') {
        this.handleReceiveDist(this.scan)
      } else {
        this.handleReceiveUC(this.scan, scanType)
      }
    },
    handleReceiveDist(distKey) {
      const params = { distKey }
      this.utils.loadShow()
      this.$ajax.get('/wm/dist/getDistByKey', { params }).then(response => {
        this.utils.loadHide()
        if (response.code == 0) {
          if (response.data.dist.flowStatus != this.getFlowNodeValue()) {
            this.$notify.warning('该配送单未处于可确认状态')
            return
          }
          this.dist = response.data.dist
          this.distItems = response.data.distItems
          this.pickItems = response.data.pickItems
          if (!this.dist.receiver) {
            const currentUser = this.$store.getters.currentUser.currentUser
            this.$set(this.dist, 'receiver', currentUser.name)
          }
          this.resetScan()
        }
      }).catch(err => {
        this.utils.loadHide()
      })
    },
    handleReceiveUC(uc, ucType) {
      if (!this.dist.id) {
        this.$notify.warning('请先扫描配送单号！')
        return
      }
      let find = false
      const pickItem = this.pickItems.map(item => {
        if (item[ucType] == uc) {
          find = true
          this.setScanedQty(item)
          this.setActiveName(uc, ucType)
        }
      })
      if (!find) {
        this.$notify.error(`未能在配送单中找到唯一码：${uc}`)
      }
      this.resetScan()
    },
    setScanedQty(pickItem) {
      this.$set(pickItem, 'scanedSkuQty', pickItem.skuQty)
      let qty = 0.0
      const filterPickItems = this.pickItems.filter(item => item.distItemId == pickItem.distItemId)
      filterPickItems.forEach(filterItem => {
        qty += filterItem.scanedSkuQty ? filterItem.scanedSkuQty : 0
      })
      const distItem = this.distItems.find(item => item.id == pickItem.distItemId)
      this.$set(distItem, 'scanedSkuQty', qty)
    },
    handleCancelPick(pickItem) {
      const params = { ids: [pickItem.id] }
      this.utils.loadShow()
      this.$ajax.delete('/wm/dist/unpick', { data: params }).then(response => {
        this.utils.loadHide()
        if (response.code == 0) {
          this.removePickItem(pickItem)
        }
      }).catch(err => {
        this.utils.loadHide()
      })
    },
    removePickItem(pickItem) {
      // delete pickItem
      this.pickItems.map((item, index) => {
        if (item.id == pickItem.id) {
          this.pickItems.splice(index, 1)
          return true
        }
      })
      // minus qty from distItem
      this.distItems.map(item => {
        if (item.id == pickItem.distItemId) {
          const qty = item.pickedSkuQty - pickItem.skuQty
          this.$set(item, 'pickedSkuQty', qty)
          return true
        }
      })
    },
    async handleFlowButtonClick(button) {
      this.flowButton = button
      const result = await this.$dialog.confirm({
        title: '流程确认',
        message: `确定要进行${button.title}操作吗？`
      })
      if (!result) return
      if (!this.dist.receiver) {
        this.$notify.error('请设置收货人！')
        this.$refs.receiverDOM.focus()
        return
      }
      this.signatureVisible = true
    },
    handleCancelSign() {
      this.signatureVisible = false
    },
    async handleSignatureComplete(image) {
      this.signatureVisible = false
      const saveEntity = {
        id: this.dist.id,
        receiver: this.dist.receiver,
        signature: image
      }
      this.utils.loadShow()
      const response = await this.$ajax.post('wm/dist/updateReceiver', saveEntity)
      if (!response.success) {
        return
      }
      const flowKey = this.propFlowKey.split(':')[0]
      const params = {
        flowKey,
        buttonKey: this.flowButton.code,
        busId: this.dist.id
      }
      this.$ajax.post('/wm/dist/flow_change', params).then(response => {
        this.utils.loadHide()
        if (response.code == 0) {
          this.$notify.success(`${this.flowButton.title}操作成功！`)
          this.clearForm()
        }
      }).catch(err => {
        this.utils.loadHide()
      })
    },
    resetScan() {
      this.scan = ''
      this.$refs.scanDom.focus()
    },
    clearForm() {
      this.dist = {}
      this.distItems = []
      this.pickItems = []
      this.signImageUrl = ''
      this.resetScan()
    }
  },
  components: {
    ReceiveItem, FlowButtons, Signature
  }

}
</script>

<style lang="scss" scoped>
  .items-container {
    min-height: 80px;
  }
  .edit-field {
    background-color: lightblue;
  }
  .btn-container {
    position: absolute;
    left:0;
    bottom: 0;
    padding:5px;
    width:100%;
    flex-direction:column ;
    display: flex;
    justify-content: space-between;
  }
  .matr-name {
    font-size:12px;
    font-weight: 600;
  }
  .matr-spec {
    font-size:12px;
  }
  .matr-qty {
    width: 40px;
    text-align: center;
    display: inline-block;
  }
  .value-container {
    height: 50px;
    display:flex;
    justify-content:left;
    align-items: center;
  }
  .icon-container {
    height: 50px;
    display:flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
  .passed {
    color: green;
  }
  .warning {
    color: orangered;
  }
</style>
